package game.editer.view;

import hx.events.Event;
import haxe.io.Path;
import hx.core.SoundFuture;
import hx.events.MouseEvent;
import game.editer.ui.CommonButton;
import hx.display.Scroll;
import hx.display.Quad;
import game.editer.ui.Config;
import hx.layout.AnchorLayoutData;
import hx.layout.AnchorLayout;
import hx.display.Label;
import hx.display.Box;
import hx.layout.FlowLayout;

/**
 * 音效选择面包
 */
class SoundSelectView extends BaseView {
	public var onSelected:String->Void;

	override function onInit() {
		super.onInit();
		var files:Array<String> = sys.FileSystem.readDirectory(EditerStage.projectSoundPath);
		files = files.filter((f) -> StringTools.endsWith(f, ".mp3"));
		trace("音频", files);
		var box = new Scroll();
		body.addChild(box);
		box.layout = new FlowLayout(10, 10);
		box.layoutData = new AnchorLayoutData(0, 0, 0, 0);
		for (file in files) {
			var item = new SoundItem(file);
			box.addChild(item);
		}
		this.addEventListener("selected_sound", onSelectedSound);
	}

	private function onSelectedSound(e:Event):Void {
		trace("选择音频", e.target);
		this.onSelected(e.target.id);
		this.remove();
	}
}

/**
 * 音效单项
 */
class SoundItem extends Box {
	public var file:String;

	public var id:String;

	public function new(file:String) {
		super();
		this.file = file;
		this.id = Path.withoutDirectory(Path.withoutExtension(file));
		this.layout = new AnchorLayout();

		var quad = new Quad(1, 36, 0x3e3e3e);
		this.addChild(quad);
		quad.width = 240;

		var label = new Label(file);
		label.textFormat = Config.COMMON_TEXT_FORMAT;
		this.addChild(label);
		label.data = file;
		label.layoutData = AnchorLayoutData.fill(5);
		label.verticalAlign = MIDDLE;

		// 播放按钮
		var button = new CommonButton("UIAtlas:play");
		this.addChild(button);
		button.layoutData = AnchorLayoutData.middleRight(0, 10);
		button.addEventListener(MouseEvent.CLICK, (e) -> {
			var sound = EditerStage.roleAssets.getSound(id);
			if (sound != null) {
				sound.root.play();
			} else {
				var soundLoader = new SoundFuture(Path.join([EditerStage.projectSoundPath, file]));
				soundLoader.onComplete((sound) -> {
					sound.root.play();
					EditerStage.roleAssets.sounds.set(id, sound);
				});
			}
			// EditerStage.roleAssets.getSound(file).root.play();
		});

		var add = new CommonButton("UIAtlas:add");
		this.addChild(add);
		add.layoutData = AnchorLayoutData.middleRight(0, 40);
		add.addEventListener(MouseEvent.CLICK, (e) -> {
			this.dispatchEvent(new Event("selected_sound", false, true));
		});
	}

	override function onInit() {
		super.onInit();
	}
}
